﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dubbo.Rpc
{
    public class RpcResult : IResult
    {
        private object result;

        private Exception exception;

        private Dictionary<string, string> attachments = new Dictionary<string, string>();

        public RpcResult()
        {
        }

        public RpcResult(object result)
        {
            this.result = result;
        }

        public RpcResult(Exception exception)
        {
            this.exception = exception;
        }

        public object recreate()
        {
            if (exception != null)
            {
                throw exception;
            }
            return result;
        }

        public object getValue()
        {
            return result;
        }

        public void setValue(object value)
        {
            this.result = value;
        }

        public Exception getException()
        {
            return exception;
        }

        public void setException(Exception e)
        {
            this.exception = e;
        }

        public bool hasException()
        {
            return exception != null;
        }

        public Dictionary<string, string> getAttachments()
        {
            return attachments;
        }

        public string getAttachment(string key)
        {
            return attachments[key];
        }

        public string getAttachment(string key, string defaultValue)
        {
            string result = attachments[key];
            if (result == null || result.Length == 0)
            {
                result = defaultValue;
            }
            return result;
        }

        public void setAttachments(Dictionary<string, string> values)
        {
            if (values != null)
            {
                foreach (var kvp in values)
                {
                    attachments.Add(kvp.Key, kvp.Value);
                }
            }
        }

        public void setAttachment(string key, string value)
        {
            attachments[key] = value;
        }

        public override string ToString()
        {
            return "RpcResult [result=" + result + ", exception=" + exception + "]";
        }
    }
}
